import 'package:flutter/material.dart';
import 'package:itoken/Components/CRouter.dart';
import 'package:itoken/Helper/HAddress.dart';
import 'package:itoken/Modle/MAddress.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SAddress with ChangeNotifier {
  var db = HAddress();

  MAddress _data = MAddress.fromMap({"id": 0});
  get data => _data;
  bool _isAddress = false;
  get isAddress => _isAddress;

  List<MAddress> _lists = [];
  get lists => _lists;

  SAddress() {
    init();
  }

  Future init() async {
    _lists = await db.getTotalList();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int saddressID = prefs.getInt('SAddressID') ?? 0;
    switch (saddressID) {
      case 0:
        if (_lists.length > 0) _data = lists.first;
        break;
      default:
        _data = lists.firstWhere((MAddress eth) {
          return eth.id == saddressID;
        });
    }
    _isAddress = _data.id > 0;
    notifyListeners();
    // print(SAddressID);
    // print(_data.id);
    // print(_data.address);
    // print(_data.private);
  }

  Future add(MAddress eth) async {
    var res = await db.saveItem(eth);
    eth.id = res;
    _data = eth;
    _isAddress = true;
    CRouter.main();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt('SAddressID', res);
    // print(res);
  }

  Future delData() async {
    await db.deleteItem(_data.id);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setInt('SAddressID', 0);
    _isAddress = false;
    CRouter.home();
  }

  @override
  void dispose() {
    super.dispose();
    db.close();
  }
}
